package com.dong.deliveryman.service;

import com.dong.basic.constant.Constant;
import com.dong.basic.dto.OrderMessageDTO;
import com.dong.basic.tools.ConnectionTools;
import com.dong.deliveryman.dao.DeliverymanDao;
import com.dong.deliveryman.enums.DeliverymanStatus;
import com.dong.deliveryman.po.DeliverymanPO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeoutException;

@Service
@Slf4j
public class MessageDeliveryService {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DeliverymanDao deliverymanDao;




    DeliverCallback callback = this::handle;

    private  void handle(String consumerTag, Delivery message) {
        log.error("deliveryman handlerMsg!");
        ConnectionFactory connectionFactory = ConnectionTools.getConnectionFactory();
        try {
            final OrderMessageDTO orderMessageDTO = objectMapper.readValue(new String(message.getBody()), OrderMessageDTO.class);
            final List<DeliverymanPO> deliverymanPOS = deliverymanDao.selectDeliverymanByStatus(DeliverymanStatus.AVAILABLE);

            orderMessageDTO.setDeliverymanId(deliverymanPOS.get(0).getId());
            log.info("订单分配骑手: {}",deliverymanPOS.get(0));
            try (Connection connection = connectionFactory.newConnection()){
                final Channel channel = connection.createChannel();
                final String msg2Send = objectMapper.writeValueAsString(orderMessageDTO);
                channel.basicPublish(Constant.Exchange.DELIVERYMAN,Constant.BindingKey.ORDER,null,msg2Send.getBytes());
            }



        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
        }
    }


    /**
     *  设置异步
     */
    @Async
    public void handleMessage()  {
        ConnectionFactory connectionFactory = ConnectionTools.getConnectionFactory();
        try (Connection connection = connectionFactory.newConnection();) {
            Channel channel = connection.createChannel();
            /**deliveryman */
            channel.exchangeDeclare(Constant.Exchange.DELIVERYMAN, BuiltinExchangeType.DIRECT,true,false,new HashMap<>());
            channel.queueDeclare(Constant.Queue.DELIVERYMAN,true,false,false,null);
            channel.queueBind(Constant.Queue.DELIVERYMAN,Constant.Exchange.DELIVERYMAN,Constant.BindingKey.DELIVERYMAN);


          //  channel.queueDeclare(Constant.Queue.ORDER,true,false,false,null);
            //绑定   快递交换机==> order==> 订单队列
            channel.queueBind(Constant.Queue.ORDER,Constant.Exchange.DELIVERYMAN,Constant.BindingKey.ORDER);


            channel.basicConsume(Constant.Queue.DELIVERYMAN,true,callback,consumerTag -> {});
            while (true) {
                Thread.sleep(1000000L);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
